// 视频类
// import {oWebControl} from './jsWebControl-1.0.0.min'
// import jsencrypt from './jsencrypt.min'
class videoClass {
  constructor(options) {
    this.state = '0' //是否可以预览  0不可以  1可以
    this.domId = 'video-container'
    this.domWidth = 800
    this.domHeight = 400
    this.oWebControl = null //视频插件交互实例

    this.appkey = '20496996' //api网关appkey
    this.secret = '3aP7Qjv5E5J39LtA1As7' //api网关secret
    this.ip = '10.192.102.55' //api网关ip
    this.port = 20443 //api网关端口

    this.enableHttps = 1 //启用https协议  0不启用 1启用
    this.playMode = 0 //0预览  1回放
    this.snapDir = 'D:/SnapDir' //抓图路径
    this.videoDir = 'D:/videoDir' //录像路径
    this.language = "zh_CN"; //语言
    this.layout = "1x1" //窗口布局
    this.showToolbar = 1 //是否显示工具条 0隐藏 1显示
    this.showSmart = 1 //是否显示智能信息 0隐藏 1显示
    let buttonIDs =
      "0,16,256,257,258,259,260,512,513,514,515,516,517,768,769"; //工具条按钮
    this.encryptedFields = [] //需要加密的字段
    this.initCount = 0 //重连计数
    this.reconnectTimes = 5 //重连次数
    this.reconnectDuration = 5 //重连间隔
    this.isResize = true //是否重新设置dom尺寸  防抖
    this.currentData = {
      wndId: 1
    } //当前选中信息
    this.currentPlayData = {} //当前播放信息
    this.resize = this.resizeDom.bind(this)
    // this._cameraIndexCodeList = ['sada12354sad'] //视频点位信息
    this._cameraIndexCodeList = [] //视频点位信息
    this.start()

  }
  // 启动
  start() {
    this.stop()
    this.addResize()
    this.setDomSize()
    this.initPlugin()
  }
  //停止
  stop() {
    this.stopPreview()
    this.unInit()
    this.hideWnd()
    this.destroyWnd()
    this.disconnect()
    this.oWebControl = null
  }
  // 添加监听窗口改变
  addResize() {
    this.removeResize()
    window.addEventListener('resize', this.resize)
  }
  // 移除监听窗口改变
  removeResize() {
    window.removeEventListener('resize', this.resize)
  }
  // 窗口改变时
  resizeDom() {
    if (this.isResize) {
      this.isResize = false
      window.requestAnimationFrame(() => {
        if (this.oWebControl) {
          this.setDomSize()
          this.oWebControl.JS_Resize(this.domWidth, this.domHeight)
          this.isResize = true
        }
      })
    }
  }
  // 设置dom容器的宽度与高度
  setDomSize() {
    this.domWidth = $("#" + this.domId).width()
    this.domHeight = $("#" + this.domId).height()
  }
  // 唤醒webControl.ext插件
  wakeUp() {
    WebControl.JS_WakeUp("VideoWebPlugin://") //固定填充
  }
  // 初始化插件
  initPlugin() {
    this.oWebControl = new WebControl({
      szPluginContainer: this.domId,
      iServicePortStart: 15900,
      iServicePortEnd: 15909,
      szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11", // 用于IE10使用ActiveX的clsid
      cbConnectSuccess: () => {
        this.initCount = 0;
        this.setCallbacks();
        this.startService()
      },
      cbConnectError: () => {
        console.log("插件初始化失败");
        this.oWebControl = null;
        $("#" + this.domId).html("插件未启动，正在尝试启动，请稍候...");
        this.wakeUp()
        this.initCount++;
        if (this.initCount < this.reconnectTimes) {
          setTimeout(() => {
            this.initPlugin()
          }, this.reconnectDuration * 1000)
        } else {
          $("#" + this.domId).html("插件启动失败，请检查插件是否安装！");
        }

      },
      cbConnectClose: function (bNormalClose) {
        this.oWebControl = null;
      }
    });
  }
  // 加载播放插件
  startService() {
    this.oWebControl.JS_StartService(
        'window', //固定填充
        {
          dllPath: './VideoPluginConnect.dll' //固定填充
        })
      .then(
        () => {
          console.log('视频服务启动成功！')
          this.createWnd()
        },
        () => {
          console.log('视频服务启动失败！')
        },
      )
  }
  // 设置消息回调
  setCallbacks() {
    if (this.oWebControl) {
      this.oWebControl.JS_SetWindowControlCallback({
        cbIntegrationCallBack: this.cbIntegrationCallBack
      });
    }
  }
  // 推送消息
  cbIntegrationCallBack(oData) {
    let responseMsg = oData.responseMsg
    let {
      type,
      msg
    } = responseMsg
    console.log(11111, type, msg)
    if (type === 1) {
      // 当前选中信息
      // console.log(11111,msg)
      // this.currentData = msg
    }
    // if (type === 2) {
    //   //当前播放信息
    //   this.currentPlayData = this.currentPlayData || {}
    //   this.currentPlayData[msg.wndId] = msg
    // }
  }
  // 创建插件窗口
  createWnd() {
    // console.log('this.domId, this.domWidth, this.domHeight', this.domId, this.domWidth, this.domHeight);
    this.oWebControl.JS_CreateWnd(this.domId, this.domWidth, this.domHeight)
      .then(
        () => {
          console.log('创建插件窗口成功！')
          this.init()
        },
        () => {
          console.log('创建插件窗口失败！')
        },
      )
  }
  // 显示插件窗口
  showWnd() {
    this.oWebControl.JS_ShowWnd()
  }
  // 隐藏插件窗口
  hideWnd() {
    if (this.oWebControl) {
      this.oWebControl.JS_HideWnd()
    }

  }
  // 申请RSA公钥
  getRSAPubKey() {
    if (this.oWebControl) {
      this.oWebControl.JS_RequestInterface({
        funcName: 'getRSAPubKey',
        argument: JSON.stringify({
          keyLength: 1024
        })
      }).then(oData => {
        console.log(oData, 110);
      })
    }
  }
  // 初始化
  init() {
    let buttonIDs = this.buttonIDs || []
    let encryptedFields = this.encryptedFields || []
    // 配置参加文档3.12.2
    this.oWebControl.JS_RequestInterface({
      funcName: 'init',
      argument: JSON.stringify({
        appkey: this.appkey,
        secret: this.secret,
        ip: this.ip,
        port: this.port,
        playMode: this.playMode,
        snapDir: this.snapDir,
        videoDir: this.videoDir,
        layout: this.layout,
        language: this.language,
        enableHTTPS: this.enableHttps,
        showToolbar: this.showToolbar,
        showSmart: this.showSmart,
        buttonIDs: this.buttonIDs,
        encryptedFields: encryptedFields.join(','),
        reconnectTimes: this.reconnectTimes,
        reconnectDuration: this.reconnectDuration
      })
    }).then((oData) => {
      this.state = '1'
      this.preview()
      this.oWebControl.JS_Resize(this.domWidth, this.domHeight); // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
    });
  }
  // 获取当前布局信息
  getLayout() {
    return this.oWebControl.JS_RequestInterface({
      funcName: "getLayout"
    }).then(function (oData) {
      let responseMsg = oData.responseMsg
      if (responseMsg.code === 0) {
        let data = JSON.parse(responseMsg.data)
        return data
      }


    })
  }
  // 设置布局信息
  setLayout(layout) {
    this.oWebControl.JS_RequestInterface({
      funcName: "setLayout",
      argument: JSON.stringify({
        layout: layout
      })
    }).then(function (oData) {
      if (oData.code === 0) {
        this.layout = layout
      } else {
        console.log('设置布局失败！')
      }
    });
  }
  // 反初始化
  unInit() {
    if (this.oWebControl) {
      this.oWebControl.JS_RequestInterface({
        funcName: "uninit"
      }).then((oData) => {
        console.log(oData)
      });
    }
  }
  set cameraIndexCodeList(value) {
    this._cameraIndexCodeList = value
    if (this.state === '1') {
      this.preview()
    }


  }
  // 视频批量预览
  preview() {
    let cameraIndexCodeList = this._cameraIndexCodeList
    let dataArr = []
    this.getLayout()
      .then(data => {
        let total = data.wndNum
        cameraIndexCodeList.forEach((code, index) => {
          let wndId = 1 + index
          wndId = (wndId % total) || total
          let codeObj = {
            cameraIndexCode: code,
            wndId
          }
          dataArr.push(codeObj)
        })
        console.log('code', dataArr)

        var tmpAgr = {
          "list": dataArr
        };
        this.oWebControl.JS_RequestInterface({
          funcName: "startMultiPreviewByCameraIndexCode",
          argument: JSON.stringify(tmpAgr)
        }).then((oData) => {
          console.log('视频预览', oData)
        });
      })

  }
  // 结束视频批量预览
  stopPreview() {

  }
  // 回放
  playback() {}
  // 销毁插件窗口
  destroyWnd() {
    if (this.oWebControl) {
      this.oWebControl.JS_DestroyWnd()
        .then(
          () => {
            console.log('销毁插件窗口成功！')
          },
          () => {
            console.log('销毁插件窗口失败！')
          },
        )
    }
  }
  // 断开插件服务连接
  disconnect() {
    if (this.oWebControl) {
      this.oWebControl.JS_Disconnect()
        .then(
          () => {
            console.log('断开与视频服务的连接成功！')
          },
          () => {
            console.log('断开与视频服务的连接失败！')
          },
        )
    }

  }
}
export default videoClass